package cn.itcast.web.aop;

//声明一个切面类

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.jms.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect //配置切面
public class LogAspect{
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;

    //配置通知类型
    @Around(value="execution(* cn.itcast.web.controller.*.*.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        //增强
        SysLog sysLog = new SysLog();
        sysLog.setTime(new Date());

        Object object= session.getAttribute("loginUser");

        if (object != null){
            User user = (User) object;
            sysLog.setUserName(user.getUserName());
            sysLog.setCompanyId(user.getCompanyId());
            sysLog.setCompanyName(user.getCompanyName());
        }
        sysLog.setIp(request.getLocalAddr()); //获取请求ip地址

        /**
         * 执行的任何方法：对应java都是method对象
         * method
         *      获取当前方法名称
         *      获取method上的所有注解
         */
        MethodSignature ms = (MethodSignature)pjp.getSignature(); //获取标记对象

        Method method = ms.getMethod();

        //2.获取当前方法名称
        String methodName = method.getName();
        sysLog.setMethod(methodName);

        //3.得到方法上的@RequestMapping注解
        if (method.isAnnotationPresent(RequestMapping.class)){
            //如果方法上存在此注解
            RequestMapping annotation = method.getAnnotation(RequestMapping.class);
            String name = annotation.name();
            sysLog.setAction(name);
        }
        sysLogService.save(sysLog);

        //调用被代理对象方法
        return pjp.proceed();
    }
}
